<?php

class FormLogin extends CFormModel
{
    public $username;
    public $password;
    public $rememberMe = false;
    private $_identity;
    private $_privilege = false;

    const PRIVILEGE_TS = 'privilege_ts';
    const PRIVILEGE_CODE = 'privilege_code';
    const PRIVILEGE_LIVE = 604800;

    public function init()
    {
        parent::init();
        $privilege_ts = Yii::app()->request->cookies[self::PRIVILEGE_TS];
        $privilege_code = Yii::app()->request->cookies[self::PRIVILEGE_CODE];
        if ($privilege_ts && $privilege_code) {
            $now = time();
            $live = $now - $privilege_ts->value;
            $code = self::privilegeCode($privilege_ts->value);
            if (($privilege_code->value == $code) && ($live < self::PRIVILEGE_LIVE)) {
                $this->_privilege = true;
            }
        }
    }

    public function rules()
    {
        return array(
            array('username, password', 'required'),
            array('rememberMe', 'boolean'),
            array('password', 'authenticate'),
        );
    }

    public function attributeLabels()
    {
        return array(
            'username' => '用户名',
            'password' => '密码',
            'rememberMe' => '两周内自动登录',
        );
    }

    /**
     * Authenticates the password.
     * This is the 'authenticate' validator as declared in rules().
     */
    public function authenticate($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $this->_identity = new UserIdentity($this->username, $this->password);
            if (!$this->_identity->authenticate()) {
                $this->addError('password', '用户名或密码不正确.');
                $msg = 'Login Error,UserName:' . $this->username . ',Passwd:' . $this->password . '.';
                Yii::log($msg, 'info', 'Login');
            }
        }
    }

    /**
     * Logs in the user using the given username and password in the model.
     * @return boolean whether login is successful
     */
    public function login()
    {
        if ($this->_identity === null) {
            $this->_identity = new UserIdentity($this->username, $this->password);
            $this->_identity->authenticate();
        }
        // 验证成功
        if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
            //设置缓存
            $duration = $this->rememberMe ? 3600 * 24 * 7 * 2 : 0; // 14 days
            Yii::app()->user->login($this->_identity, $duration);
            $user_id = $this->_identity->getUserId();
            //
            if (!$this->_privilege) {
                $now = time();
                $expire = $now + self::PRIVILEGE_LIVE;
                $cookie_ts = new CHttpCookie(self::PRIVILEGE_TS, $now);
                $cookie_ts->expire = $expire;
                Yii::app()->request->cookies[self::PRIVILEGE_TS] = $cookie_ts;
                $cookie_code = new CHttpCookie(self::PRIVILEGE_CODE, self::privilegeCode($now));
                $cookie_code->expire = $expire;
                Yii::app()->request->cookies[self::PRIVILEGE_CODE] = $cookie_code;
            }
            //设置login时间
            $user = User::model()->findByPk($user_id);
            $user->last_login_time = date("Y-m-d H:i:s", time());
            $user->last_login_ip = Curl::getUserIp();
            $user->save();

            // 设置session范围内的属性
            //Yii::app()->user->setState('userid', $this->_identity->getId());
            //Yii::app()->user->setState('roles', "");

            return true;
        } else {
            return false;
        }
    }

    public function getPrivilege()
    {
        return $this->_privilege;
    }

    public static function privilegeCode($str)
    {
        return md5($str . 'S8fsEDFfgW3');
    }
}
